package org.yylnb.openplatform.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.yylnb.openplatform.commons.utlis.CommonsResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * 时间戳过滤器
 *
 * @author RainLin
 * @date 2020/7/24 - 18:07
 */
@Component
public class TimeStampFilter extends ZuulFilter {
    private final ObjectMapper objectMapper;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public TimeStampFilter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public String filterType() {

        //前置过滤器
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        //这个过滤器的目的也是在路由之前进行校验,所有它的顺序一定是在路由之前,
        //但是系统参数需要首先帮我们判定用户有没有传递时间戳,所以这个过滤器应该在系统参数之后
        return 75;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {

        //获取到请求的发起时间
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        //获取到用户传递的请求时间
        String requestTime = request.getParameter("requestTime");
        //获取到当前服务器时间
        long currentTimeMillis = System.currentTimeMillis();

        boolean isOk = true;
        try {
            //判断时间是否过期
            long time = simpleDateFormat.parse(requestTime).getTime();
            if (time > currentTimeMillis || currentTimeMillis - time > 60000) {
                isOk = false;
            }

        } catch (ParseException e) {
            //代表用户传递的格式不对
            isOk = false;
            e.printStackTrace();
        }

        if (!isOk) {
            //不符合要求
            context.setSendZuulResponse(false);
            HttpServletResponse response = context.getResponse();
            response.setContentType("application/json;charset=utf-8");

            try {
                context.setResponseBody(objectMapper.writeValueAsString(CommonsResult.ERROR.msg("时间戳不合法")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}


